<template>
  <div v-if="visible" class="add-member-modal" @click="closeModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ isEditing ? '编辑成员' : '添加新成员' }}</h3>
        <button @click="closeModal" class="close-btn">&times;</button>
      </div>
      
      <form @submit.prevent="handleSubmit" class="member-form">
        <div class="form-sections">
          <!-- 基本信息 -->
          <div class="form-section">
            <h4>基本信息</h4>
            <div class="form-row">
        <div class="form-group">
                <label for="name">姓名 *</label>
          <input 
            id="name" 
            v-model="formData.name" 
                  type="text" 
            required
                  placeholder="请输入姓名"
          >
              </div>
              <div class="form-group">
                <label for="gender">性别 *</label>
                <select id="gender" v-model="formData.gender" required>
                  <option value="">请选择性别</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
        </div>
        
            <div class="form-row">
        <div class="form-group">
          <label for="birthDate">出生日期</label>
          <input 
            id="birthDate" 
            v-model="formData.birthDate"
                  type="date"
                >
              </div>
              <div class="form-group">
                <label for="generation">世代</label>
                <input 
                  id="generation"
                  v-model.number="formData.generation" 
                  type="number" 
                  min="1"
                  placeholder="第几代"
                >
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="relationshipType">关系类型</label>
                <select id="relationshipType" v-model="formData.relationshipType">
                  <option value="亲生">亲生</option>
                  <option value="继子">继子</option>
                  <option value="养子">养子</option>
                  <option value="过继">过继</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div class="form-group">
                <label for="maritalStatus">婚姻状态</label>
                <select id="maritalStatus" v-model="formData.maritalStatus">
                  <option value="未婚">未婚</option>
                  <option value="已婚">已婚</option>
                  <option value="离异">离异</option>
                  <option value="丧偶">丧偶</option>
                  <option value="再婚">再婚</option>
                </select>
              </div>
            </div>
            
            <div class="form-group">
              <label>
                <input 
                  type="checkbox" 
                  v-model="formData.isAlive"
                >
                在世
              </label>
            </div>
            
            <div v-if="!formData.isAlive" class="form-group">
              <label for="deathDate">逝世日期</label>
              <input 
                id="deathDate"
                v-model="formData.deathDate" 
                type="date"
              >
            </div>
          </div>
          
          <!-- 联系信息 -->
          <div class="form-section">
            <h4>联系信息</h4>
            <div class="form-group">
              <label for="address">地址</label>
              <input 
                id="address"
                v-model="formData.address" 
                type="text" 
                placeholder="请输入地址"
          >
        </div>
        
            <div class="form-row">
              <div class="form-group">
                <label for="phone">电话</label>
                <input 
                  id="phone"
                  v-model="formData.phone" 
                  type="tel" 
                  placeholder="请输入电话号码"
                >
              </div>
              <div class="form-group">
                <label for="email">邮箱</label>
                <input 
                  id="email"
                  v-model="formData.email" 
                  type="email" 
                  placeholder="请输入邮箱地址"
                >
              </div>
            </div>
          </div>
          
          <!-- 职业信息 -->
          <div class="form-section">
            <h4>职业信息</h4>
            <div class="form-row">
              <div class="form-group">
                <label for="occupation">职业</label>
                <input 
                  id="occupation"
                  v-model="formData.occupation" 
                  type="text" 
                  placeholder="请输入职业"
                >
              </div>
              <div class="form-group">
                <label for="education">教育程度</label>
                <select id="education" v-model="formData.education">
                  <option value="">请选择教育程度</option>
                  <option value="小学">小学</option>
                  <option value="初中">初中</option>
                  <option value="高中">高中</option>
                  <option value="大专">大专</option>
                  <option value="本科">本科</option>
                  <option value="硕士">硕士</option>
                  <option value="博士">博士</option>
                  <option value="其他">其他</option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- 家族关系 -->
          <div class="form-section">
            <h4>家族关系</h4>
            
            <!-- 父母关系 -->
            <div class="relationship-group">
              <h5>父母</h5>
              <div class="form-row">
                <div class="form-group">
                  <label for="fatherId">父亲</label>
                  <select id="fatherId" v-model="formData.fatherId">
                    <option value="">请选择父亲</option>
                    <option 
                      v-for="member in availableFathers" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="motherId">母亲</label>
                  <select id="motherId" v-model="formData.motherId">
                    <option value="">请选择母亲</option>
                    <option 
                      v-for="member in availableMothers" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
              </div>
            </div>
            
            <!-- 配偶关系 -->
            <div class="relationship-group">
              <h5>配偶</h5>
              <div class="form-group">
                <label for="spouseId">配偶</label>
                <select id="spouseId" v-model="formData.spouseId">
                  <option value="">请选择配偶</option>
                  <option 
                    v-for="member in availableSpouses" 
                    :key="member.id" 
                    :value="member.id"
                  >
                    {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                  </option>
                </select>
              </div>
            </div>
            
            <!-- 继父母关系 -->
            <div class="relationship-group">
              <h5>继父母</h5>
              <div class="form-row">
                <div class="form-group">
                  <label for="stepFatherId">继父</label>
                  <select id="stepFatherId" v-model="formData.stepFatherId">
                    <option value="">请选择继父</option>
                    <option 
                      v-for="member in availableStepFathers" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="stepMotherId">继母</label>
                  <select id="stepMotherId" v-model="formData.stepMotherId">
                    <option value="">请选择继母</option>
                    <option 
                      v-for="member in availableStepMothers" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
              </div>
            </div>
            
            <!-- 养父母关系 -->
            <div class="relationship-group">
              <h5>养父母</h5>
              <div class="form-row">
                <div class="form-group">
                  <label for="adoptiveFatherId">养父</label>
                  <select id="adoptiveFatherId" v-model="formData.adoptiveFatherId">
                    <option value="">请选择养父</option>
                    <option 
                      v-for="member in availableAdoptiveFathers" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="adoptiveMotherId">养母</label>
                  <select id="adoptiveMotherId" v-model="formData.adoptiveMotherId">
                    <option value="">请选择养母</option>
                    <option 
                      v-for="member in availableAdoptiveMothers" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
              </div>
            </div>
            
            <!-- 兄弟姐妹关系 -->
            <div class="relationship-group">
              <h5>兄弟姐妹</h5>
              <div class="form-row">
                <div class="form-group">
                  <label for="elderBrotherId">兄长</label>
                  <select id="elderBrotherId" v-model="formData.elderBrotherId">
                    <option value="">请选择兄长</option>
                    <option 
                      v-for="member in availableElderBrothers" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="elderSisterId">姐姐</label>
                  <select id="elderSisterId" v-model="formData.elderSisterId">
                    <option value="">请选择姐姐</option>
                    <option 
                      v-for="member in availableElderSisters" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
              </div>
            </div>
            
            <!-- 其他关系 -->
            <div class="relationship-group">
              <h5>其他关系</h5>
              <div class="form-row">
                <div class="form-group">
                  <label for="cousinId">堂表兄弟</label>
                  <select id="cousinId" v-model="formData.cousinId">
                    <option value="">请选择堂表兄弟</option>
                    <option 
                      v-for="member in availableCousins" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
                    </option>
                  </select>
                </div>
        <div class="form-group">
                  <label for="guardianId">监护人</label>
                  <select id="guardianId" v-model="formData.guardianId">
                    <option value="">请选择监护人</option>
                    <option 
                      v-for="member in availableGuardians" 
                      :key="member.id" 
                      :value="member.id"
                    >
                      {{ member.name }} ({{ member.gender }}, {{ member.generation }}代)
            </option>
          </select>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 描述信息 -->
          <div class="form-section">
            <h4>描述信息</h4>
            <div class="form-group">
              <label for="description">描述</label>
              <textarea 
                id="description"
                v-model="formData.description" 
                rows="3"
                placeholder="请输入成员描述"
              ></textarea>
            </div>
            
            <div class="form-group">
              <label for="notes">备注</label>
              <textarea 
                id="notes"
                v-model="formData.notes" 
                rows="3"
                placeholder="请输入备注信息"
              ></textarea>
            </div>
          </div>
        </div>
        
        <div class="form-actions">
          <button type="button" @click="closeModal" class="btn secondary">取消</button>
          <button type="submit" class="btn primary" :disabled="loading">
            {{ loading ? '保存中...' : (isEditing ? '更新' : '添加') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue';

export default {
  name: 'AddMemberForm',
  props: {
    member: {
      type: Object,
      default: null
    },
    members: {
      type: Array,
      default: () => []
    },
    visible: {
      type: Boolean,
      default: false
    },
    isEditing: {
      type: Boolean,
      default: false
    }
  },
  emits: ['save', 'close', 'error'],
  setup(props, { emit }) {
    const loading = ref(false);
    
    // 表单数据
    const formData = reactive({
      name: '',
      gender: '',
      birthDate: '',
      deathDate: '',
      isAlive: true,
      generation: null,
      relationshipType: '亲生',
      maritalStatus: '未婚',
      occupation: '',
      education: '',
      address: '',
      phone: '',
      email: '',
      description: '',
      notes: '',
      // 关系字段
      fatherId: null,
      motherId: null,
      spouseId: null,
      stepFatherId: null,
      stepMotherId: null,
      adoptiveFatherId: null,
      adoptiveMotherId: null,
      elderBrotherId: null,
      elderSisterId: null,
      youngerBrotherId: null,
      youngerSisterId: null,
      cousinId: null,
      guardianId: null
    });
    
    // 计算可选的成员
    const availableFathers = computed(() => 
      props.members.filter(m => m.gender === '男' && m.id !== props.member?.id)
    );
    
    const availableMothers = computed(() => 
      props.members.filter(m => m.gender === '女' && m.id !== props.member?.id)
    );
    
    const availableSpouses = computed(() => 
      props.members.filter(m => m.id !== props.member?.id)
    );
    
    const availableStepFathers = computed(() => 
      props.members.filter(m => m.gender === '男' && m.id !== props.member?.id)
    );
    
    const availableStepMothers = computed(() => 
      props.members.filter(m => m.gender === '女' && m.id !== props.member?.id)
    );
    
    const availableAdoptiveFathers = computed(() => 
      props.members.filter(m => m.gender === '男' && m.id !== props.member?.id)
    );
    
    const availableAdoptiveMothers = computed(() => 
      props.members.filter(m => m.gender === '女' && m.id !== props.member?.id)
    );
    
    const availableElderBrothers = computed(() => 
      props.members.filter(m => m.gender === '男' && m.id !== props.member?.id)
    );
    
    const availableElderSisters = computed(() => 
      props.members.filter(m => m.gender === '女' && m.id !== props.member?.id)
    );
    
    const availableCousins = computed(() => 
      props.members.filter(m => m.id !== props.member?.id)
    );
    
    const availableGuardians = computed(() => 
      props.members.filter(m => m.id !== props.member?.id)
    );
    
    // 初始化表单数据
    const initFormData = () => {
      if (props.member && props.isEditing) {
        Object.assign(formData, {
          name: props.member.name || '',
          gender: props.member.gender || '',
          birthDate: props.member.birthDate || '',
          deathDate: props.member.deathDate || '',
          isAlive: props.member.isAlive !== undefined ? props.member.isAlive : true,
          generation: props.member.generation || null,
          relationshipType: props.member.relationshipType || '亲生',
          maritalStatus: props.member.maritalStatus || '未婚',
          occupation: props.member.occupation || '',
          education: props.member.education || '',
          address: props.member.address || '',
          phone: props.member.phone || '',
          email: props.member.email || '',
          description: props.member.description || '',
          notes: props.member.notes || '',
          fatherId: props.member.fatherId || null,
          motherId: props.member.motherId || null,
          spouseId: props.member.spouseId || null,
          stepFatherId: props.member.stepFatherId || null,
          stepMotherId: props.member.stepMotherId || null,
          adoptiveFatherId: props.member.adoptedFatherId || props.member.adoptiveFatherId || null,
          adoptiveMotherId: props.member.adoptedMotherId || props.member.adoptiveMotherId || null,
          elderBrotherId: props.member.elderBrotherId || null,
          elderSisterId: props.member.elderSisterId || null,
          youngerBrotherId: props.member.youngerBrotherId || null,
          youngerSisterId: props.member.youngerSisterId || null,
          cousinId: props.member.cousinId || null,
          guardianId: props.member.guardianId || null
        });
      } else {
        // 重置表单
        Object.assign(formData, {
          name: '',
          gender: '',
          birthDate: '',
          deathDate: '',
          isAlive: true,
          generation: null,
          relationshipType: '亲生',
          maritalStatus: '未婚',
          occupation: '',
          education: '',
          address: '',
          phone: '',
          email: '',
          description: '',
          notes: '',
          fatherId: null,
          motherId: null,
          spouseId: null,
          stepFatherId: null,
          stepMotherId: null,
          adoptiveFatherId: null,
          adoptiveMotherId: null,
          elderBrotherId: null,
          elderSisterId: null,
          youngerBrotherId: null,
          youngerSisterId: null,
          cousinId: null,
          guardianId: null
        });
      }
    };
    
    // 监听成员变化
    watch(() => props.member, initFormData, { immediate: true });
    
    // 监听编辑状态变化
    watch(() => props.isEditing, initFormData);
    
    // 表单验证
    const validateForm = () => {
      if (!formData.name.trim()) {
        throw new Error('姓名不能为空');
      }
      
      if (!formData.gender) {
        throw new Error('请选择性别');
      }
      
      if (formData.birthDate && formData.deathDate) {
        const birthDate = new Date(formData.birthDate);
        const deathDate = new Date(formData.deathDate);
        if (deathDate <= birthDate) {
          throw new Error('逝世日期不能早于或等于出生日期');
        }
      }
      
      if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        throw new Error('邮箱格式不正确');
      }
      
      return true;
    };
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        loading.value = true;
        
        // 验证表单
        validateForm();
        
        // 自动加上familyTreeId（假设为1）
        formData.familyTreeId = 1;
        // 处理日期字段
        if (!formData.birthDate || formData.birthDate === 'Invalid date') formData.birthDate = null;
        if (!formData.deathDate || formData.deathDate === 'Invalid date') formData.deathDate = null;
        // 构造最终提交数据，确保familyTreeId一定存在
        const submitData = { ...JSON.parse(JSON.stringify(formData)), familyTreeId: 1 };
        console.log('最终提交成员数据:', submitData);
        
        // 发送事件
        emit('save', submitData);
        
      } catch (error) {
        console.error('表单提交错误:', error);
        emit('error', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 关闭模态框
    const closeModal = () => {
      emit('close');
    };
    
    return {
      loading,
      formData,
      availableFathers,
      availableMothers,
      availableSpouses,
      availableStepFathers,
      availableStepMothers,
      availableAdoptiveFathers,
      availableAdoptiveMothers,
      availableElderBrothers,
      availableElderSisters,
      availableCousins,
      availableGuardians,
      handleSubmit,
      closeModal
    };
  }
};
</script>

<style scoped>
.add-member-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  max-width: 800px;
  max-height: 90vh;
  width: 90%;
  overflow-y: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.member-form {
  padding: 20px;
}

.form-sections {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.form-section {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
}

.form-section h4 {
  margin: 0 0 20px 0;
  color: #333;
  border-bottom: 2px solid #4CAF50;
  padding-bottom: 8px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: bold;
  color: #333;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.relationship-group {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.relationship-group h5 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.primary {
  background-color: #4CAF50;
  color: white;
}

.primary:hover:not(:disabled) {
  background-color: #45a049;
}

.secondary {
  background-color: #f4f4f4;
  color: #333;
  border: 1px solid #ddd;
}

.secondary:hover {
  background-color: #e7e7e7;
}

@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    margin: 10px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>